package session.stateless;

import entity.Customer;
import entity.SaleQuotation;
import entity.LineItem;
import entity.Product;
import entity.SaleInquiry;
import entity.SaleLead;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class SaleQuotationBean implements SaleQuotationBeanLocal {
    @PersistenceContext()
    EntityManager em;
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    @EJB
    private DiscountBeanLocal discountBeanLocal;
    
    NumberFormat formatter = new DecimalFormat("#0.00");
 
    
    public LineItem createLineItem_Discount(Product product,Long quantity) {
        LineItem lineItem = new LineItem();

        lineItem.setLineItemQuantity(quantity);
        lineItem.setProduct(product);
        
        Double discountRate=discountBeanLocal.calculateDiscountRate(product.getProductType(), quantity);
        Double finalPrice =product.getProductPrice()*quantity* (1-discountRate/100);    
        lineItem.setFinalPrice(new Double(formatter.format(finalPrice)));
        
        em.persist(lineItem);
        em.flush();
        
        return lineItem;
    }
    
    private void deleteLineItem(Long lineItemId) {
        LineItem lineItem = em.find(LineItem.class, lineItemId);
        if (lineItem == null) {
            System.out.println("Line Item does not exist!");
        } else {
            lineItem.setProduct(null);
            em.remove(lineItem);
            em.flush();
        }
    }
    
    public List<Product> getProduct() {
        Query q = em.createQuery("SELECT c FROM Product c");
        return q.getResultList();
    }
    
    public Long convertToSaleQuotation(Long saleInquiryId, List<LineItem> lineItems){
        SaleQuotation saleQuotation = new SaleQuotation();
        SaleInquiry saleInquiry = em.find(SaleInquiry.class,saleInquiryId);        
        SaleLead saleLead = saleInquiry.getSaleLead();
        
        saleQuotation.setSaleLead(saleLead);
        
        Date date = new Date();
        saleQuotation.setSaleInquiryDate(dateFormat.format(date));
        Double totalPrice = new Double(0);
        
        List<LineItem> temp_lineItems = new ArrayList<LineItem>();
        for (LineItem lineItem:lineItems)
        {
            if ((lineItem.getLineItemQuantity()!=null)&&(lineItem.getLineItemQuantity()>=0))
            {
                LineItem item = createLineItem_Discount(lineItem.getProduct(), lineItem.getLineItemQuantity());
                totalPrice += item.getFinalPrice();
                temp_lineItems.add(item);
            }   
        }        

        saleQuotation.setLineItems(temp_lineItems); 
        saleQuotation.setTotalPrice(new Double(formatter.format(totalPrice)));

        em.persist(saleQuotation);
        
        saleLead.getSaleQuotations().add(saleQuotation);
        em.flush();
        
        return saleQuotation.getId();
    }

    public Long createNewSaleQuotation(String registrationNumber, List<LineItem> Items, Integer leadTime) {
        Query query=em.createQuery("SELECT s from SaleLead s WHERE s.registrationNumber =:registrationNumber");
        query.setParameter("registrationNumber", registrationNumber);
        
        SaleLead saleLead = (SaleLead)query.getSingleResult();
        
        if(saleLead==null)
            return new Long(0);        
        else
        {
            SaleQuotation saleQuotation = new SaleQuotation();
            Double totalPrice = new Double(0); 
            
            for (LineItem lineItem:Items)
            {
                if (lineItem.getLineItemQuantity()!=0)
                {
                    totalPrice += lineItem.getFinalPrice();
                }
            }
            saleQuotation.setLineItems(Items);
            saleQuotation.setTotalPrice(new Double(formatter.format(totalPrice)));
            
            Date date = new Date();
            saleQuotation.setSaleInquiryDate(dateFormat.format(date));
            saleQuotation.setSaleLead(saleLead);
            saleQuotation.setLeadTime(leadTime);
            
            em.persist(saleQuotation);
            
            saleLead.getSaleQuotations().add(saleQuotation);
            em.flush();
            
            return saleQuotation.getId();
        }
    }

    public void updateSaleQuotation(Long saleQuotationId,List<LineItem> lineItems) {
        SaleQuotation saleQuotation = em.find(SaleQuotation.class, saleQuotationId);

        List<LineItem> temp_LineItem = saleQuotation.getLineItems();
        saleQuotation.setLineItems(null);
        for (LineItem lineItem : temp_LineItem) {
            deleteLineItem(lineItem.getLineItemId());
        }

        Double totalPrice = new Double(0);
        List<LineItem> temp = new ArrayList<LineItem>();

        for (LineItem item : lineItems) {
            if ((item.getLineItemQuantity() != null) & (item.getLineItemQuantity() > 0)) {
                LineItem lt = createLineItem_Discount(item.getProduct(), item.getLineItemQuantity());
                temp.add(lt);
                totalPrice += lt.getFinalPrice();
            }
        }

        saleQuotation.setLineItems(temp);
        saleQuotation.setTotalPrice(new Double(formatter.format(totalPrice)));
        em.flush();
    }

    public void deleteSaleQuotation(Long saleQuotationId) {
        SaleQuotation saleQuotation = em.find(SaleQuotation.class, saleQuotationId);
        if (saleQuotation == null) {
            System.out.println("Delete sale quotation error!");
        } else {
            List<LineItem> temp = saleQuotation.getLineItems();
            saleQuotation.setLineItems(null);

            for (LineItem lineItem : temp) {
                deleteLineItem(lineItem.getLineItemId());
            }

            saleQuotation.getSaleLead().getSaleQuotations().remove(saleQuotation);
            em.remove(saleQuotation);
            em.flush();
        }
    }

    public List<SaleQuotation> getSaleQuotation() {
        Query q = em.createQuery("SELECT c FROM SaleQuotation c");
        return q.getResultList();
    }

    public List<SaleQuotation> getSaleQuotationBySaleLead(String registrationNumber) {
        SaleLead saleLead = em.find(SaleLead.class, registrationNumber);
        return (List<SaleQuotation>) saleLead.getSaleQuotations();
    }

    public List<SaleQuotation> getSaleQuotationByCustomer(String registrationNumber) {
        Customer customer = em.find(Customer.class, registrationNumber);
        return (List<SaleQuotation>) customer.getSaleQuotations();
    }

    public double calculateFinalPrice(Product product, Long quantity) {
        Double discountRate=discountBeanLocal.calculateDiscountRate(product.getProductType(), quantity);
        Double finalPrice =product.getProductPrice()*quantity* (1-discountRate/100);    
        return finalPrice;
        
    }
}
